Skip to main content

Return confusion

In this lesson, we'll go over a common misunderstanding about returning within a function that contains a .forEach() call.

But first, let's go over how to name variables when iterating.

Naming variables

Using a clear name for variables makes it much easier for you and others to understand the code. This is especially true when it comes to iteration.

As a result, it's always a good idea to use the plural for the array and the singular for the array item. Here are a couple of examples:

marks => item is mark people => item is person

It may appear to be a minor point, but it makes a significant difference!💡

Here is an example,

const marks = [10, 14, 15]; // array (plural)
grades.forEach(function (mark) {
// array item (singular)
console.log(grade);
});

const Names = ["Sam", "Alex"]; // array (plural)
Names.forEach(function (Name) {
// array item (singular)
console.log(Name);
});

Returning from loop

When attempting to return from a function that contains a forEach call, a common error occurs. This is due to the fact that there are two functions.

Assume you have the following function:

function logUserAges(userAges) {
userAges.forEach(function (userAge) {
console.log(userAge);
});
}

and you want this function to return true when it's finished. Where should the return true be placed?

Would that be,

function logUserAges(userAges) {
userAges.forEach(function (userAge) {
console.log(userAge);
return true; // does this work as expected?
});
}

or

function logUserAges(userAges) {
userAges.forEach(function (userAge) {
console.log(userAge);
});
return true; // or is this the correct way?
}

When we take a step back, we can see that the return keyword returns from its own function. As a result, the first approach is ineffective. Because you're returning from the callback function received by .forEach(). The logUserAges function will not return anything.

As a result, the correct answer is the second option:

function logUserAges(userAges) {
userAges.forEach(function (userAge) {
console.log(userAge);
});
return true; // ✅ return from the logUserAges function
}

The return true inside the function is not very useful because it will return from the callback function, but there is no more code inside that function anyway. The next iteration of the .forEach() will still take place. Also, no matter what you return inside of the .forEach() method, it will always return undefined.

One more example

Let's take another example,

function logStrings(strings) {
strings.forEach(function (string) {
console.log(string);
return "Inside callback function";
});
return "Outside callback function";
}

Is the function going to return 10 or 20?

The function will return "Outside callback function" because it is returning from the outer function.